import React from 'react';
import {
  Row,
  Col,
  Tree,
  Select,
  Button,
  Input,
  Form,
  DatePicker,
  Spin,
  Table,
  Pagination,
  TreeSelect,
  message,
  Modal
} from 'antd';
const { confirm } = Modal;
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  UserOutlined,
  CloseOutlined,
} from '@ant-design/icons';
// import { Page } from 'components'
import styles from './index.less';
import { connect } from 'dva';

import AddModal from './addModal';
// import RoleModal from './roleModal';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import _ from 'lodash'

import defaultSettings from '../../../../config/defaultSettings'

@Form.create()
@connect(({ system }) => ({ ...system }))
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currSystemId: '',
      currOrgName: '',
      timestamp: '',
      checkColumns: [
        { title: '机构名称', dataIndex: 'name', key: 'name', width: 200, },
        { title: '机构编号', dataIndex: 'orgCode', key: 'orgCode', width: 200, },
        { title: '状态', dataIndex: 'statusCd', key: 'statusCd', width: 200, render: (text, record) => <span style={{color: text==1?'green':'red'}}>{text==1?'有效':'无效'}</span> },
        { title: '创建时间', dataIndex: 'createdDt', key: 'createdDt', width: 200, render: (text, record) => <span>{text?text:''}</span>},
        {
          title: '操作',
          dataIndex: 'cz',
          width: 200,
          render: (text, record) => (
            <p className={styles.tableBtns}>
              <a onClick={() => this.addFun(record.id)}>
                <PlusOutlined />
                新增
              </a>
              <a onClick={() => this.updateData(record)}>
                <EditOutlined />
                修改
              </a>
              <a onClick={() => this.deleteData(record)}>
                <CloseOutlined />
                删除
              </a>
            </p>
          ),
        },
      ],
      dataList: [],
      orgList: [],
      tableStatus: 0,
      totalPage: 1,
      totalData: 1,
      currentPage: 1,
      loading: false,
      // selectedRowKeys: [],
      addModalVisible: false,
      addTimestamp: Date.parse(new Date()),
      addLoading: false,

      systemNameList: [],

      tableData: [],

      roleTimestamp: Date.parse(new Date()),
      roleModalVisible: false,
      roleLoading: false,
      deptDetail: {}, //当前用户详情
      pwdVisible: false,
      currPwdTitle: '',
      resetPwdLoading: false,

      currParentId: 0
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.querySystemNameList();
  };

  //获取用户列表
  querySever = async () => {
    this.setState({ loading: true });
    const { props } = this;
    await props
      .dispatch({
        type: 'system/queryDeptList',
        payload: {
          orgName: this.state.currOrgName,
          systemId: this.state.currSystemId,
          // parentId: this.state.currParentId
        },
      })
      .then(res => {
        if(this.state.currOrgName==''){
          let parents = res.filter(
            value => value.pid == 0 || value.pid == null
          );
          let childrens = res.filter(
            value => value.pid !== 0 && value.pid != null
          );
          for(let i=0;i<res.length;i++){
            res[i].key = res[i].id
          }
          this.setState({
            loading: false,
            orgList: res?res:[],
            totalData: res.length,
            dataList: this.toTreeData(parents, childrens),
          });
        }else{
          this.setState({
            loading: false,
            orgList: res?res:[],
            totalData: res.length,
            dataList: res?res:[],
          });
        }
      });
  };

  fliterEvent= (parents, childrens) => {
    parents.forEach(parent => {
      childrens.forEach((current, index) => {
        if (current.pid === parent.id) {
          let temp = JSON.parse(JSON.stringify(childrens));
          temp.splice(index, 1);
          this.fliterEvent([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };

  toTreeData = (parents,childrens)=>{
      this.fliterEvent(parents, childrens);
      console.log(parents,'-----------------------------')
      return parents;
  }
  
  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'system/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        this.setState({
          systemNameList: res.list ? res.list : [],
          currSystemId: (defaultSettings.systemId&&defaultSettings.systemId!='')?defaultSettings.systemId: (res.list? res.list[0].systemId : ''),
        },()=>{
          this.querySever();
        });
      });
  };

  //系统名称修改
  systemIdChange = value => {
    this.setState({
      currSystemId: value,
    });
  };

  //权限名称修改
  orgNameChange = e => {
    this.setState({
      currOrgName: e.target.value,
    });
  };

  //提交订单
  submitFun = () => {
    this.init();
    this.setState({
      tableStatus: this.state.currOrgName==''?0:1
    })
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currSystemId: '',
        currOrgName: '',
        timestamp: Date.parse(new Date()) + 1,
        tableStatus: 0
      },
      () => {
        this.init();
      },
    );
  };

  //修改信息
  updateData = record => {
    this.setState({
      deptDetail: record,
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  //删除信息
  deleteData = record => {
    const _this = this;
    confirm({
      content: `确认删除【${record.name}】?`,
      onOk() {
        console.log('OK');
        const { dispatch } = _this.props;
        dispatch({
          type: 'system/deleteDeptPost',
          payload: {
            orgId: record.id
          },
        }).then(res => {
          if(res.success){
            if (res.code == 0) {
              message.success('删除成功！');
            } else {
              message.error(res.msg);
            }
            _this.init()
          }else {
            message.error(res.msg);
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.init();
      },
    );
  };

  get addModalProps() {
    const { addModalVisible, deptDetail, addLoading } = this.state;
    let _this = this;
    return {
      title: '机构管理',
      visible: addModalVisible,
      deptDetail: deptDetail,
      loading: addLoading,
      width: '450px',
      okText: '提交',
      cancelText: '取消',
      onOk: data => {
        _this.setState(
          {
            addLoading: true,
          },
          () => {
            const { dispatch } = _this.props;
            let payload = data.orgId==''?Object.assign({},deptDetail,data): Object.assign({},{orgId: deptDetail.id},data)
            dispatch({
              type: data.orgId==''?'system/addDeptPost':'system/editDeptPost',
              payload: payload,
            }).then(res => {
              if(res.success){
                if (res.code == 0) {
                  message.success(data.orgId==''?'新增成功！':'修改成功！');
                } else {
                  message.error(res.msg);
                }
                _this.setState(
                  {
                    addLoading: false,
                    addModalVisible: false,
                  },
                  () => {
                    _this.init();
                  },
                );
              }else {
                message.error(res.msg);
              }
            });
          },
        );
      },
      onCancel() {
        _this.setState({
          addModalVisible: false,
        });
      },
    };
  }

  //新增用户
  addFun = (id) => {
    this.setState({
      deptDetail: {
        parentId: id,
        orgName: '',
        // orgLevel: 2,
        systemId: this.state.currSystemId,
      },
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  expandedRowRenderFun = (id) => {
    this.setState({
      currParentId: id
    },()=>{
      this.querySever()
    })
    console.log(id,'id')
  }

  render() {
    const { checkColumns, dataList, addTimestamp, roleTimestamp, systemNameList, timestamp } = this.state;

    const { getFieldDecorator } = this.props.form;

    // const rowSelection = {
    //   selectedRowKeys,
    //   onChange: this.onSelectChange,
    // };
    return (
      <PageHeaderWrapper title={false} breadcrumb={false}>
      <div className={styles.mainPage}>
        <Row>
          <Col span={24}>
            <dl key={timestamp+1}>
              <dt>
                <Form name="horizontal_search" layout="inline">
                {
                  (!defaultSettings.systemId||defaultSettings.systemId=='')&&
                  <Form.Item name="systemId" label="系统名称">
                    <Select
                      style={{ width: 200 }}
                      placeholder="请选择系统名称"
                      onChange={this.systemIdChange}
                      value={this.state.currSystemId}
                    >
                      {
                        systemNameList.map(item=>{
                          return(<Option value={item.systemId}>{item.systemName}</Option>)
                        })
                      }
                    </Select>
                  </Form.Item>
                }
                  <Form.Item name="currOrgName" label="机构名称">
                    <Input
                      style={{ width: 200 }}
                      type="text"
                      placeholder="请输入名称搜索"
                      defaultValue={this.state.currOrgName}
                      onChange={this.orgNameChange}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" onClick={this.submitFun}>
                      <SearchOutlined />
                      搜索
                    </Button>
                    <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                      <SyncOutlined />
                      重置
                    </Button>
                  </Form.Item>
                  <Form.Item style={{ float: 'right', marginRight: 0 }}>
                    <Button type="primary" onClick={()=>this.addFun(0)}>
                      <PlusOutlined />
                      新增
                    </Button>
                  </Form.Item>
                </Form>
              </dt>
              <dd>
                <AddModal key={addTimestamp} {...this.addModalProps} />
                <Spin spinning={this.state.loading}>
                    <Table
                      style={{ marginTop: '20px' }}
                      bordered
                      columns={checkColumns}
                      dataSource={dataList}
                      pagination={false}
                    />
                </Spin>
                {/* <p style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Pagination
                    current={this.state.currentPage}
                    total={this.state.totalData}
                    onChange={this.pageChange}
                  />
                </p> */}
              </dd>
            </dl>
          </Col>
        </Row>
      </div>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
